<script lang="ts" setup name="AddForm">
import { ref } from 'vue'
import { _ } from 'iking-utils'
import { useFormRules } from '@g/hooks/use-rules'
import type { addFormData, addFormParams } from '../interface'
import { addForm, editForm, getFormById } from '@/MainApp/apis/manage-design'
import '../design.scss'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  activeVal: {
    type: String,
    default: 'first'
  },
  editData: {
    type: Object,
    default: () => null
  },
  listData: {
    type: Object,
    default: () => null
  },
  serverFields: {
    type: Array,
    default: () => []
  },
  interfacesForm: {
    type: Object,
    default: () => null
  },
  groupInterfaces: {
    type: Array,
    default: () => []
  }
})
const emits = defineEmits<{
  (event: 'cancel'): void
  (event: 'update:visible'): void
  (event: 'confirm'): void
}>()
const { msgSuccess, msgError } = useMessage()
const { t } = useConfig()
const { lenContent, lenName } = useLength()
const dVisible = ref(false)
const addFormDesigner = ref()
const addNameFormRef = ref()
const addNameForm = ref<addFormData>({
  dsModel: 0
})
const addFormVisible = ref(false)
const dsModel = ref(0)
const addNameRules = useFormRules([
  {
    key: 'name',
    required: true,
    trigger: 'blur',
    msg: '请输入表名'
  }
])
let editFormData: any = null
const fieldsList = ref(props.serverFields)
const urlName = ref('')
const title = ref('')
const baseUrl = ref(import.meta.env.VITE_APP_API_BASEURL)
// const showUrlName = ref(false)
const loading = ref(false)
const dsModelOptions = [
  { label: '通用数据源', value: 0 },
  { label: '功能数据源', value: 1 }
]
watch(
  () => props.visible,
  async visible => {
    if (visible) {
      if (props.activeVal !== 'third')
        title.value = props.editData ? '编辑界面' : '新建界面'
      else title.value = props.editData ? '编辑表单' : '新建表单'
      if (props.editData) {
        const { data, success } = await getFormById(props.editData.id)
        if (success) {
          urlName.value = data.url
          if (import.meta.env.DEV)
            baseUrl.value = data.url || useHttpUrl().baseUrl

          addNameForm.value = { ...data }
          editFormData = JSON.parse(data.json)
          if (!addFormVisible.value && !!props.editData)
            addFormDesigner.value?.setFormJson(editFormData)
        }
      }
      else {
        addNameForm.value = {
          dsModel: 0
        }
      }
      if (props.serverFields)
        fieldsList.value = props.serverFields
      addFormDesigner.value?.setFormJson(props.interfacesForm)
    }
    else {
      urlName.value = ''
      addFormDesigner.value?.designer?.clearDesigner()
    }
    dVisible.value = visible
  }
)
watch(
  () => props.serverFields,
  async serverFields => {
    fieldsList.value = serverFields
  }
)
onUpdated(async () => {
  if (dVisible.value && !addFormVisible.value)
    addFormDesigner.value?.setFormJson(props.interfacesForm)

  if (dVisible.value && !addFormVisible.value && !!props.editData)
    addFormDesigner.value?.setFormJson(editFormData)

  if (!dVisible.value && !addFormVisible.value)
    addFormDesigner.value?.clearDesigner()
})
const handCancel = () => {
  dVisible.value = false
  addFormVisible.value = false
  addFormDesigner.value?.clearDesigner()
  emits('update:visible')
}
const handClosed = () => {
  dVisible.value = false
  addFormVisible.value = false
  addFormDesigner.value?.clearDesigner()
  emits('cancel')
  handCancel()
}
const handConfirm = async () => {
  addFormVisible.value = true
}
const handAddClosed = () => {
  addNameForm.value = {}
  addFormVisible.value = false
}
const setFormDataJson = (json: any, val: any) => {
  const formJson = _.cloneDeep(json)
  if (formJson.formConfig.dataSources.length > 0) {
    formJson.formConfig.dataSources = formJson.formConfig.dataSources.map(
      (item: any) => {
        props.groupInterfaces.forEach((ele: any) => {
          if (val === 0 && item.type === ele.type && ele.common) {
            item.requestURL = ele.requestURL
            item.headers = _.cloneDeep(ele.headers)
            if (item.type === 'PAGE')
              item.dataHandlerCode = ele.dataHandlerCode
          }
          if (val === 1 && item.type === ele.type && !ele.common)
            item.requestURL = ele.requestURL
        })
        return {
          ...item
        }
      }
    )
  }
  return formJson
}
const addFormConfirm = async () => {
  const data = await addNameFormRef.value.validate((valid: boolean) => {
    if (valid)
      return true
    else return false
  })
  if (data) {
    const formJson = addFormDesigner.value.getFormJson()
    // formJson = setFormDataJson(formJson, addNameForm.value.dsModel)
    const params: addFormParams = {
      url: urlName.value,
      scaffoldType: 'FORM',
      scaffoldTypeName: '表单',
      ...addNameForm.value,
      json: JSON.stringify(formJson)
    }
    if (props.listData)
      params.moduleId = props.listData.id

    if (props.editData)
      params.id = props.editData.id
    loading.value = true
    const { success, msg } = props.editData
      ? await editForm(params)
      : await addForm(params)
    if (success) {
      emits('confirm')
      addNameForm.value = {}
      dVisible.value = false
      addFormVisible.value = false
      loading.value = false
      addFormDesigner.value?.clearDesigner()
      msgSuccess(msg)
    }
    else {
      loading.value = false
      msgError(msg)
    }
  }
}
const changeUrlName = (val: any) => {
  baseUrl.value = val.target.value
}
// const handHelpFilled = () => {
//   showUrlName.value = !showUrlName.value
// }

const dsModelChange = (val: any) => {
  let formJson = addFormDesigner.value.getFormJson()
  formJson = setFormDataJson(formJson, val)
  addFormDesigner.value?.setFormJson(formJson)
}
</script>

<template>
  <el-dialog
    v-model="dVisible"
    class="form-design"
    :title="title"
    width="99%"
    top="10px"
    :close-on-click-modal="false"
    :append-to-body="true"
    align-center
    @closed="handClosed"
  >
    <template #header>
      <el-row>
        <el-col :span="3" class="elfz">
          <span>{{ title }}</span>
        </el-col>
        <el-col :span="21" class="elfz">
          <!-- <el-button
            type="primary"
            :icon="HelpFilled"
            text
            @click="handHelpFilled"
          /> -->
          <p>切换数据源</p>
          <el-select
            v-model="dsModel"
            class="wm-2 elurl"
            placeholder="切换数据源"
            @change="dsModelChange"
          >
            <el-option
              v-for="item in dsModelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <p v-if="dsModel === 1">配置调试地址</p>
          <el-input
            v-if="dsModel === 1"
            v-model.trim="urlName"
            class="elurl"
            type="text"
            @blur="changeUrlName"
          />
        </el-col>
      </el-row>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handCancel">{{ t('action.cancel') }}</el-button>
        <el-button type="primary" @click="handConfirm">
          {{ t('action.sure') }}
        </el-button>
      </span>
    </template>
    <v-form-designer
      v-if="dVisible"
      ref="addFormDesigner"
      :global-dsv="{ apiHost: baseUrl }"
      :server-fields="fieldsList"
    />
  </el-dialog>
  <el-dialog
    v-model="addFormVisible"
    title="添加名称描述"
    width="600px"
    draggable
    :close-on-click-modal="false"
    :append-to-body="true"
    @closed="handAddClosed"
  >
    <el-form
      ref="addNameFormRef"
      :model="addNameForm"
      :rules="addNameRules"
      label-width="120px"
    >
      <el-row>
        <el-col :span="24" class="elcol">
          <el-form-item label="名称" prop="name">
            <el-input
              v-model.trim="addNameForm.name"
              clearable
              :maxlength="lenName"
              show-word-limit
              placeholder="请输入名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="elcol">
          <el-form-item label="切换数据源" prop="dsModel">
            <el-select
              v-model="addNameForm.dsModel"
              class="wm-2 elurl"
              placeholder="切换数据源"
              @change="dsModelChange"
            >
              <el-option
                v-for="item in dsModelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="elcol">
          <el-form-item label="描述" prop="description">
            <el-input
              v-model.trim="addNameForm.description"
              :rows="2"
              :maxlength="lenContent"
              show-word-limit
              type="textarea"
              placeholder="请输入描述"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handCancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="addFormConfirm">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.manage-design {
  padding: 15px;

  .elcolTitle {
    padding: 15px;
    border-bottom: 1px solid #e5e5e5;
    margin-bottom: 15px;

    .projectTitle {
      font-size: 16px;
      font-weight: 400;
      color: #333;
      padding-left: 10px;
      border-left: 5px solid #409eff;
    }
  }

  .dataTable {
    padding: 15px;
  }
}

.elfz {
  display: flex;
  align-items: center;
  justify-content: flex-start;

  p {
    margin-left: 15px;
  }

  .elurl {
    margin-left: 15px;
    width: 200px !important;
  }
}
</style>
